package com.toocms.jinjuhang.ui.login.register

import android.app.Application
import android.os.Bundle
import android.os.CountDownTimer
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.TextPaint
import android.text.TextUtils
import android.text.style.ClickableSpan
import android.view.View
import androidx.databinding.ObservableBoolean
import androidx.databinding.ObservableField
import com.blankj.utilcode.util.ColorUtils
import com.blankj.utilcode.util.StringUtils
import com.toocms.jinjuhang.R
import com.toocms.jinjuhang.config.Constants
import com.toocms.jinjuhang.config.Urls
import com.toocms.jinjuhang.config.UserRepository
import com.toocms.jinjuhang.data.User
import com.toocms.jinjuhang.ui.login.LoginFgt
import com.toocms.jinjuhang.ui.mine.setting.agreement.AgreementFgt
import com.toocms.jinjuhang.utils.FragmentUtils
import com.toocms.jinjuhang.widget.view_model.requestData
import com.toocms.tab.base.BaseModel
import com.toocms.tab.base.BaseViewModel
import com.toocms.tab.binding.command.BindingAction
import com.toocms.tab.binding.command.BindingCommand

class RegisterModel(application: Application, bundle: Bundle?) :
    BaseViewModel<BaseModel>(application) {
    var timer: Timer? = null
    val openId by lazy {
        bundle?.getString(Constants.BundleKey.KEY_OPEN_ID) ?: ""
    }
    val unionId by lazy {
        bundle?.getString(Constants.BundleKey.KEY_UNION_ID) ?: ""
    }
    val avatar by lazy {
        bundle?.getString(Constants.BundleKey.KEY_AVATAR) ?: ""
    }
    val nickname by lazy {
        bundle?.getString(Constants.BundleKey.KEY_NICKNAME) ?: ""
    }
    val accountObservableField = ObservableField<String>()
    val verifyObservableField = ObservableField<String>()
    val passwordObservableField = ObservableField<String>()
    val rePasswordObservableField = ObservableField<String>()
    val memberSnObservableField = ObservableField<String>()
    val isCanGetVerifyCodeObservableBoolean = ObservableBoolean(true)
    val getVerifyCodeHintObservableField by lazy {
        ObservableField(StringUtils.getString(R.string.str_get_verify_code))
    }
    val agreementObservableField by lazy {
        val userAgreement = "《用户协议》"
        val content = SpannableStringBuilder("注册即同意$userAgreement").apply {
            setSpan(
                object : ClickableSpan() {
                    override fun onClick(widget: View) {
                        val params= Bundle()
                        params.putString(Constants.BundleKey.KEY_TYPE,Constants.Extra.AGREEMENT_TYPE_USER)
                        startFragment(AgreementFgt::class.java,params)
                    }

                    override fun updateDrawState(ds: TextPaint) {
//                        super.updateDrawState(ds)
                        ds.color = ColorUtils.getColor(R.color.clr_main)
                        ds.isUnderlineText = false
                    }
                },
                length - userAgreement.length,
                length,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
            )
        }
        ObservableField(content)
    }

    val getVerifyCodeClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
        val account = accountObservableField.get()
        if (TextUtils.isEmpty(account)) {
            showToast(R.string.str_no_input_login_mobile_hint)
            return@BindingAction
        }
        val params = mutableMapOf<String, String?>()
        params["account"] = account
        params["unique_code"] = Constants.UniqueCode.REGISTER
        requestData(
            Urls.Verify.GET_VERIFY,
            params,
            resultClass = String::class.java,
            isShowLoading = true,
            result = {
                showToast(it)
                timer?.cancel()
                timer = Timer()
                timer?.start()
            })
    })

    val registerClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
        val params = mutableMapOf<String, String?>()
        params["account"] = accountObservableField.get()
        params["verify"] = verifyObservableField.get()
        params["password"] = passwordObservableField.get()
        params["re_password"] = rePasswordObservableField.get()
        params["member_sn"] = memberSnObservableField.get()
        params["unionid"] = unionId
        params["openid"] = openId
        params["avatar"] = avatar
        params["nickname"] = nickname
        requestData(
            Urls.Login.REGISTER,
            params,
            resultClass = User::class.java,
            isShowLoading = true,
            result = {
                UserRepository.updateUser(it)
                UserRepository.setLogin(true)
                FragmentUtils.popTo(LoginFgt::class.java, true)
            })
    })

    override fun onStop() {
        super.onStop()
        timer?.cancel()
    }

    //------------------------------------------------内部类-----------------------------------------

    inner class Timer : CountDownTimer(
        Constants.Extra.REGAIN_VERIFY_CODE_TIME,
        Constants.Extra.COUNT_DOWN_INTERVAL
    ) {
        override fun onTick(millisUntilFinished: Long) {
            isCanGetVerifyCodeObservableBoolean.set(false)
            getVerifyCodeHintObservableField.set("${StringUtils.getString(R.string.str_regain)}(${millisUntilFinished / 1000}s)")
        }

        override fun onFinish() {
            isCanGetVerifyCodeObservableBoolean.set(true)
            getVerifyCodeHintObservableField.set("${StringUtils.getString(R.string.str_regain)}")
        }

    }

}